package com.qiujie.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.StrUtil;
import com.qiujie.dto.Response;
import com.qiujie.dto.ResponseDTO;
import com.qiujie.entity.Dish;
import com.qiujie.service.DishService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.net.URLEncoder;

/**
 * 饮食控制器
 */
@RestController
@RequestMapping("/dish")
@Api(tags = "饮食管理")
public class DishController {

    private static final String filePath = System.getProperty("user.dir") + "/dish/";

    @Value("${server.port:8888}")
    private String port;

    @Value("${ip:localhost}")
    private String ip;

    @Autowired
    private DishService dishService;

    @PostMapping("/add")
    @ApiOperation("添加饮食")
    @PreAuthorize("hasAnyAuthority('dish:add')")
    public ResponseDTO add(@RequestBody Dish dish) {
        return this.dishService.add(dish);
    }

    @PutMapping("/update")
    @ApiOperation("更新饮食")
    @PreAuthorize("hasAnyAuthority('dish:update')")
    public ResponseDTO update(@RequestBody Dish dish) {
        return this.dishService.update(dish);
    }

    @DeleteMapping("/delete/{id}")
    @ApiOperation("删除饮食")
    @PreAuthorize("hasAnyAuthority('dish:delete')")
    public ResponseDTO delete(@PathVariable Integer id) {
        return this.dishService.delete(id);
    }

    @GetMapping("/list")
    @ApiOperation("获取饮食列表")
    public ResponseDTO list(@RequestParam(required = false) String name, 
                           @RequestParam(required = false) Integer categoryId) {
        return this.dishService.list(name, categoryId);
    }

    @GetMapping("/detail/{id}")
    @ApiOperation("获取饮食详情")
    public ResponseDTO getDetail(@PathVariable Integer id) {
        return this.dishService.getDetail(id);
    }

    @PutMapping("/status/{id}/{status}")
    @ApiOperation("更新饮食状态")
    @PreAuthorize("hasAnyAuthority('dish:status')")
    public ResponseDTO updateStatus(@PathVariable Integer id, @PathVariable Integer status) {
        return this.dishService.updateStatus(id, status);
    }

//    @PostMapping("/upload/image")
//    @ApiOperation("上传食谱图片")
//    @PreAuthorize("hasAnyAuthority('dailymenu:update')")
//    public ResponseDTO uploadImage(
//            @ApiParam(value = "图片文件", required = true) @RequestParam("file") MultipartFile file) {
//        return this.dishService.uploadImage(file);
//    }

    @PostMapping("/upload/image")
    @ApiOperation("上传食谱图片")
    @PreAuthorize("hasAnyAuthority('dailymenu:update')")
    public ResponseDTO upload(MultipartFile file) {
        String flag;
        synchronized (DishController.class) {
            flag = System.currentTimeMillis() + "";
            ThreadUtil.sleep(1L);
        }
        String fileName = file.getOriginalFilename();
        try {
            if (!FileUtil.isDirectory(filePath)) {
                FileUtil.mkdir(filePath);
            }
            // 文件存储形式：时间戳-文件名
            FileUtil.writeBytes(file.getBytes(), filePath + flag + "-" + fileName);  // ***/manager/files/1697438073596-avatar.png
            System.out.println(fileName + "--上传成功");

        } catch (Exception e) {
            System.err.println(fileName + "--文件上传失败");
        }
        String http = "http://" + ip + ":" + port + "/dish/";
        return Response.success(http + flag + "-" + fileName);
    }

    /**
     * 获取文件
     *
     * @param flag
     * @param response
     */
    @GetMapping("/{flag}")   //  1697438073596-avatar.png
    public void avatarPath(@PathVariable String flag, HttpServletResponse response) {
        OutputStream os;
        try {
            if (StrUtil.isNotEmpty(flag)) {
                response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(flag, "UTF-8"));
                response.setContentType("application/octet-stream");
                byte[] bytes = FileUtil.readBytes(filePath + flag);
                os = response.getOutputStream();
                os.write(bytes);
                os.flush();
                os.close();
            }
        } catch (Exception e) {
            System.out.println("文件下载失败");
        }
    }

} 